package tps12.axwax.client.widgets;

import java.util.Collection;

import tps12.axwax.client.PuzzleClientImpl;
import tps12.axwax.client.PuzzleClient.PuzzleDescription;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * Composite widget for selecting a puzzle.
 * 
 * @author Travis
 *
 */
public class SelectPuzzle extends Composite {
	/**
	 * Constructs a puzzle selection widget.
	 */
	public SelectPuzzle() {
		final VerticalPanel container = new VerticalPanel();
		initWidget(container);
		
		final VerticalPanel panel = new VerticalPanel();
		container.add(panel);
		
		HorizontalPanel selectWidgets = new HorizontalPanel();
		panel.add(selectWidgets);
		
		final ListBox puzzles = new ListBox();
		
		final Button select = new Button();
		select.setText("Select");
				
		new PuzzleClientImpl(new PuzzleClientImpl.GwtRequestBuilderFactory())
			.getPuzzleList(new AsyncCallback<Collection<PuzzleDescription>>() {
			@Override public void onFailure(Throwable caught) {
				GWT.log("Get puzzle list failed", caught);
			}

			@Override public void onSuccess(Collection<PuzzleDescription> result) {
				puzzles.clear();
				for (PuzzleDescription puzzle : result)
					puzzles.addItem(puzzle.title, puzzle.url);
			}
		});

		selectWidgets.add(puzzles);
		
		select.addClickHandler(new ClickHandler() {
			@Override public void onClick(ClickEvent event) {
				History.newItem("solve=" + puzzles.getValue(puzzles.getSelectedIndex()));
			}
		});
		selectWidgets.add(select);
	}
}
